import { defineComponent, onMounted, ref, unref, watch } from 'vue'
import citysList from '@province-city-china/level'
import { Items, props, PropsType } from './type'

// console.log(123, citys ist)
// const citysList = require('@province-city-china/level')
import './index.scss'

const only = ['82', '81', '50', '31', '12', '11'] //白名单
export default defineComponent({
  name: 'M-CitySelect',
  props: props,
  emits: ['update:modelValue', 'change'],
  // expose: ['setValue', 'resetVale'],
  setup(props: PropsType, { slots, emit, expose }) {
    const { type, customerStyle, customerProps, customerCprops } = props
    // console.log('city', citysList)
    const options = ref<Items[]>([])
    const val = ref<any>(type == 1 ? '' : [])

    //@注释
    //@name: 获取type对应的中文
    //@params:
    //@des:
    const getPlaceText = ['', '省份', '市', '地区', '区域']

    //@备注:  props 选项
    //@取值:
    const cprop = {
      value: 'code',
      label: 'name',
      children: 'children',
      multiple: false,
      checkStrictly: type == 4,
      emitPath: true, //要使得change 函数生效所以强制显示全部的路径
      ...customerCprops
    }
    //@备注:Cascader 属性
    //@取值:
    const prop = {
      'show-all-levels': true,
      'collapse-tags-tooltip': true,
      'collapse-tags': true,
      placeholder: `请选择所在${getPlaceText[type]}`,
      clearable: true,
      ...customerProps
    }

    //@注释
    //@name:选择城市回调
    //@params:val  选择回调值 string | Array[string]
    //@des:
    const changeSelectCity = (val: any): void => {
      let res = {
        data: val,
        result: ''
      }
      // console.log('res222', val)
      if (cprop.multiple) {
        switch (type) {
          case 1:
            // 省级
            res = {
              data: val,
              result: val
            }
            break

          default:
            // 省级 市级 县级  type==2 || type==3
            res = {
              data: val,
              result: (val as any)!.map((it: string) => {
                return it[it.length - 1]
              })
            }
            break
        }
      } else {
        if (type == 1) {
          res = {
            data: val,
            result: val
          }
        } else {
          res = {
            data: val,
            result: val[val.length - 1]
          }
        }
      }
      // debugger
      emit('change', res)
      emit('update:modelValue', res.result)
    }

    //@注释
    //@name:渲染选项
    //@params:
    //@des:
    const renderOptions = () => {
      const ops = unref(options)
      // console.log('options.value', ops)
      return ops.map((item: any) => {
        // console.log('typeOf item', typeof item)
        return <el-option key={item.code} label={item.name} value={item.code} />
      })
    }

    // @注释
    // @name:
    // @params:
    // @des:初始化选型
    const getSelectOption = () => {
      // 如果是1 只拿省的数据
      if (type === 1) {
        getProvinceList()
      } else if (type === 2) {
        //省市数据
        getCitysList()
      } else {
        //全部数据
        options.value = getAllArea(citysList)
      }
    }

    // 获取所有城市三级全部数据
    const getAllArea = (arr: Array<any>): any => {
      const res: Items[] = []

      arr.map((item: any) => {
        // console.log(6666, typeof(item.d) )
        const obj: Items = {
          name: item.name,
          code: item.code
        }

        if (item.children && typeof item.children === 'object') {
          obj.children = getAllArea(item.children)
        }
        res.push(obj)
      })
      return res
    }

    // 获取省级数据
    const getProvinceList = () => {
      const res: Items[] = []
      citysList.forEach((item) => {
        const obj: Items = {
          code: item.code,
          name: item.name
        }

        res.push(obj)
      })
      options.value = res
      // console.log(123, options.value)
      // debugger
    }
    // 获取省市数据
    const getCitysList = () => {
      const res: any = []
      citysList.forEach((item) => {
        const obj: Items = {
          code: '',
          name: '',
          children: []
        }
        obj.code = item.code
        obj.name = item.name
        item.children!.forEach((val) => {
          const or: any = {}
          or.code = val.code
          or.name = val.name
          obj.children!.push(or)
        })
        res.push(obj)
      })
      options.value = res
    }

    // 地域编码 转为三位地域数组地区多选用到
    const arr2area = (arr: Array<string>) => {
      if (!arr[0]) {
        return
      }
      const str = arr[0]
      let a = str.slice(0, 2)
      let b = str.slice(2, 4)
      let c = str.slice(4, 6)
      c = `${a}${b}${c}`
      b = `${a}${b}00`
      a = `${a}0000`
      return [a, b, c].slice(0, type)
    }

    //@注释
    //@name: 地区编码 转为数组
    //@params:
    //@des:
    const code2area = (str: string) => {
      let a = str.slice(0, 2)
      let b = str.slice(2, 4)
      let c = str.slice(4, 6)
      const spec = only.includes(a)
      c = `${a}${b}${c}`
      b = `${a}${b}00`
      a = `${a}0000`
      if (spec) {
        // 特殊省份
        return [a, c].slice(0, type)
      } else {
        return [a, b, c].slice(0, type)
      }
    }

    // @注释
    // @name:
    // @params:
    // @des:重置
    const resetVale = () => {
      if (type === 1) {
        val.value = ''
      } else {
        val.value = []
      }
      changeSelectCity(val.value)
    }
    // @注释
    // @name:直接设置 默认值   溯级处理
    // @params: treeLevel true-需要溯级   false  直接赋值
    // @des:
    const setValue = (v: any, treeLevel = false) => {
      if (cprop.multiple && (typeof v === 'string' || typeof v === 'number')) {
        console.error('多选状态下 ,默认值必须为数组')
        return
      }
      if (!treeLevel) {
        if (cprop.multiple) {
          // debugger
          let arr = []
          switch (type) {
            case 1:
              val.value = v
              // debugger
              break
            case 2:
              arr = (v as any).map((it: string) => {
                return code2area(it[it.length - 1])
              })
              val.value = arr
              break
            case 3:
              arr = (v as any).map((it: string) => {
                return code2area(it[it.length - 1])
              })
              val.value = arr
              break
            default:
              break
          }
        } else {
          val.value = v
          // debugger
        }
      } else {
        let arr
        // 自动构造数据
        switch (type) {
          case 1:
            // 省级
            val.value = v
            break
          case 2:
            // 省级 市级
            arr = v.map((it: string) => {
              return code2area(it)
            })
            if (cprop.multiple) {
              val.value = arr
            } else {
              val.value = arr[0]
            }
            break
          case 3:
            // 省级 市级 县级
            arr = v.map((it: string) => {
              return code2area(it)
            })
            if (cprop.multiple) {
              val.value = arr
            } else {
              val.value = arr[0]
            }
            break
          default:
            break
        }
      }
      changeSelectCity(val.value)
    }
    onMounted(async () => {
      await getSelectOption()
      val.value = props.modelValue
    })

    watch(
      () => props.modelValue,
      (value: any) => {
        // console.log('val,old', val, old)
        // alert(val)
        const str = Array.isArray(value)
          ? JSON.stringify(value)
          : value.toString()
        const loca = val.value.toString()
        // console.log('val,old', value)
        if (str != loca) {
          val.value = value
        }
      }
    )
    expose({
      resetVale,
      setValue
    })
    return () => {
      return (
        <div>
          {/* {type} */}
          {type == 1 ? (
            <el-select
              v-model={val.value}
              {...prop}
              multiple={cprop.multiple}
              style={customerStyle}
              onChange={changeSelectCity}
            >
              {renderOptions()}
            </el-select>
          ) : (
            <el-cascader
              v-model={val.value}
              options={options.value}
              props={cprop}
              {...prop}
              style={customerStyle}
              onChange={changeSelectCity}
            />
          )}
        </div>
      )
    }
  }
})
